"""
计算器历史记录管理模块
提供计算历史的存储、检索和管理功能
"""
from datetime import datetime
from typing import List, Optional, Callable
import json
import os


class HistoryEntry:
    """历史记录条目"""
    
    def __init__(self, expression: str, result: str, timestamp: Optional[datetime] = None):
        """
        初始化历史记录条目
        
        Args:
            expression: 计算表达式
            result: 计算结果
            timestamp: 时间戳，如果为None则使用当前时间
        """
        self.expression = expression
        self.result = result
        self.timestamp = timestamp or datetime.now()
    
    def __str__(self) -> str:
        """字符串表示"""
        return f"{self.expression} = {self.result}"
    
    def get_formatted_string(self, include_time: bool = False) -> str:
        """
        获取格式化的字符串表示
        
        Args:
            include_time: 是否包含时间信息
        """
        if include_time:
            time_str = self.timestamp.strftime("%H:%M:%S")
            return f"[{time_str}] {self.expression} = {self.result}"
        else:
            return f"{self.expression} = {self.result}"
    
    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            "expression": self.expression,
            "result": self.result,
            "timestamp": self.timestamp.isoformat()
        }
    
    @classmethod
    def from_dict(cls, data: dict) -> "HistoryEntry":
        """从字典创建历史记录条目"""
        timestamp = datetime.fromisoformat(data["timestamp"])
        return cls(data["expression"], data["result"], timestamp)


class HistoryManager:
    """计算器历史记录管理器"""
    
    def __init__(self, max_entries: int = 100, callback: Optional[Callable[[List[HistoryEntry]], None]] = None):
        """
        初始化历史记录管理器
        
        Args:
            max_entries: 最大历史记录条目数
            callback: 历史记录变化时的回调函数
        """
        self._history: List[HistoryEntry] = []
        self._max_entries = max_entries
        self._callback = callback
    
    def add_entry(self, expression: str, result: str) -> None:
        """
        添加新的历史记录条目
        
        Args:
            expression: 计算表达式
            result: 计算结果
        """
        entry = HistoryEntry(expression, result)
        self._history.append(entry)
        
        # 如果超过最大条目数，删除最老的记录
        if len(self._history) > self._max_entries:
            self._history.pop(0)
        
        self._notify_change()
    
    def get_all_entries(self) -> List[HistoryEntry]:
        """获取所有历史记录条目"""
        return self._history.copy()
    
    def get_recent_entries(self, count: int) -> List[HistoryEntry]:
        """
        获取最近的N条历史记录
        
        Args:
            count: 要获取的条目数
        """
        return self._history[-count:] if count <= len(self._history) else self._history.copy()
    
    def get_entry_count(self) -> int:
        """获取历史记录条目总数"""
        return len(self._history)
    
    def get_entry_by_index(self, index: int) -> Optional[HistoryEntry]:
        """
        根据索引获取历史记录条目
        
        Args:
            index: 条目索引
        """
        if 0 <= index < len(self._history):
            return self._history[index]
        return None
    
    def clear_history(self) -> None:
        """清空所有历史记录"""
        self._history.clear()
        self._notify_change()
    
    def remove_entry(self, index: int) -> bool:
        """
        删除指定索引的历史记录条目
        
        Args:
            index: 要删除的条目索引
            
        Returns:
            是否成功删除
        """
        if 0 <= index < len(self._history):
            self._history.pop(index)
            self._notify_change()
            return True
        return False
    
    def search_entries(self, keyword: str) -> List[HistoryEntry]:
        """
        搜索包含关键词的历史记录条目
        
        Args:
            keyword: 搜索关键词
        """
        results = []
        keyword_lower = keyword.lower()
        
        for entry in self._history:
            if (keyword_lower in entry.expression.lower() or 
                keyword_lower in entry.result.lower()):
                results.append(entry)
        
        return results
    
    def get_formatted_history(self, include_time: bool = False, reverse: bool = True) -> List[str]:
        """
        获取格式化的历史记录字符串列表
        
        Args:
            include_time: 是否包含时间信息
            reverse: 是否倒序（最新的在前）
        """
        entries = self._history.copy()
        if reverse:
            entries.reverse()
        
        return [entry.get_formatted_string(include_time) for entry in entries]
    
    def set_callback(self, callback: Callable[[List[HistoryEntry]], None]) -> None:
        """
        设置历史记录变化的回调函数
        
        Args:
            callback: 回调函数，参数为历史记录列表
        """
        self._callback = callback
    
    def set_max_entries(self, max_entries: int) -> None:
        """
        设置最大历史记录条目数
        
        Args:
            max_entries: 最大条目数
        """
        self._max_entries = max_entries
        
        # 如果当前条目数超过新的最大值，删除多余的旧记录
        while len(self._history) > self._max_entries:
            self._history.pop(0)
        
        self._notify_change()
    
    def _notify_change(self) -> None:
        """通知历史记录变化"""
        if self._callback:
            self._callback(self._history.copy())
    
    def save_to_file(self, filename: str) -> bool:
        """
        将历史记录保存到文件
        
        Args:
            filename: 文件名
            
        Returns:
            是否保存成功
        """
        try:
            data = {
                "history": [entry.to_dict() for entry in self._history],
                "max_entries": self._max_entries,
                "saved_at": datetime.now().isoformat()
            }
            
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)
            
            return True
        except Exception:
            return False
    
    def load_from_file(self, filename: str) -> bool:
        """
        从文件加载历史记录
        
        Args:
            filename: 文件名
            
        Returns:
            是否加载成功
        """
        try:
            if not os.path.exists(filename):
                return False
            
            with open(filename, 'r', encoding='utf-8') as f:
                data = json.load(f)
            
            # 清空当前历史记录
            self._history.clear()
            
            # 加载历史记录条目
            for entry_data in data.get("history", []):
                entry = HistoryEntry.from_dict(entry_data)
                self._history.append(entry)
            
            # 更新最大条目数
            if "max_entries" in data:
                self._max_entries = data["max_entries"]
            
            self._notify_change()
            return True
            
        except Exception:
            return False
    
    def export_to_text(self, filename: str, include_time: bool = True) -> bool:
        """
        将历史记录导出为文本文件
        
        Args:
            filename: 文件名
            include_time: 是否包含时间信息
            
        Returns:
            是否导出成功
        """
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                f.write("计算器历史记录\n")
                f.write("=" * 50 + "\n\n")
                
                for entry in reversed(self._history):
                    f.write(entry.get_formatted_string(include_time) + "\n")
                
                f.write(f"\n总计: {len(self._history)} 条记录")
            
            return True
        except Exception:
            return False
    
    def __len__(self) -> int:
        """获取历史记录条目数"""
        return len(self._history)
    
    def __str__(self) -> str:
        """字符串表示"""
        return f"HistoryManager({len(self._history)} entries, max={self._max_entries})"